package com.apes.framework.plugin.condition.model;

import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.condition.PricingProcedureContext;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
 * 功能：定价过程- 定义如何链接条件类型，由多个条件类型组成，每个一条件类型就是一个定位步骤
 *
 * @author xul
 * @create 2018-11-06 17:24
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = PricingProcedure.CONST_TABLE_NAME)
public class PricingProcedure extends BaseModel {
    public static final String CONST_TABLE_NAME = "tech_pricing_procedure";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "定价过程")
    @Comment("编号")
    private String id;

    @Column(name = "name", nullable = false, length = 120)
    @Comment("描述")
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "pricing_type_id", nullable = false, referencedColumnName = "id")
    @Comment("定价类型")
    private PricingType pricingType;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "usage_id", nullable = false, referencedColumnName = "id")
    @Comment("用途")
    private Usage usage;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "application_id", nullable = false, referencedColumnName = "id")
    @Comment("应用")
    private Application application;

    @OneToMany(mappedBy = "pricingProcedure", cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderBy("step asc")
    private Set<PricingProcedureItem> pricingProcedureItems = new HashSet();

    public Set<PricingProcedureItem> getPricingProcedureItems() {
        for (PricingProcedureItem item : pricingProcedureItems) {
            item.setPricingProcedure(this);
        }
        return pricingProcedureItems;
    }

    /**
     * 定价过程执行
     */
    public void process(final PricingProcedureContext context) {
        for (PricingProcedureItem item : pricingProcedureItems) {
            context.setPricingProcedure(this);
            item.process(context);
            context.addProcedure(context.getCurrentProcedure());
        }
    }

}
